package com.bestv.search.common.util;

import net.paoding.analysis.analyzer.PaodingAnalyzer;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertySetStrategy;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;

import java.io.*;
import java.sql.Blob;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {
    private static Logger logger = Logger.getLogger(CommonUtil.class);

    public static String convert(Blob blob) {
        return convert(blob, null);
    }

    public static String convert(Blob blob, String streamEncoding) {
        StringBuffer content = new StringBuffer();
        BufferedReader br = null;
        try {
            // Gets blob as binary stream
            InputStream input = blob.getBinaryStream();
            if (input != null) {
                InputStreamReader inReader = null;
                if (streamEncoding != null) {
                    inReader = new InputStreamReader(input, streamEncoding);
                } else {
                    inReader = new InputStreamReader(input);
                }
                br = new BufferedReader(inReader);

                // Convert stream to string
                String line = null;
                while ((line = br.readLine()) != null) {
                    content.append(line);
                }
            }
        } catch (Exception e) {
            logger.error("Convert blob object to string failed, " + e.getMessage());
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();
    }

    public static boolean isNumber(String s) {
        if (s == null) {
            return false;
        }

        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher match = pattern.matcher(s);
        return match.matches();
    }

    public static boolean isLetter(String s) {
        if (s == null) {
            return false;
        }

        Pattern pattern = Pattern.compile("[A-Z]|[a-z]");
        Matcher match = pattern.matcher(s);
        return match.matches();
    }

    @SuppressWarnings("deprecation")
    public static String splitTokenByPaoding(String word) {
        StringBuffer sb = new StringBuffer();
        PaodingAnalyzer analyzer = new PaodingAnalyzer();
        StringReader reader = new StringReader(word);
        TokenStream ts = analyzer.tokenStream("", reader);
        Token token;
        try {
            while ((token = ts.next()) != null) {
                String text = ChineseCharToEn.getAllFirstLetter(token.term());
                sb.append(text).append(" ").append(CharUtil.charToNum(text)).append(" ");
            }
        } catch (IOException e) {
            logger.error(e);
        }
        return sb.toString();
    }

    public static <T> List<T> convertJSONStrTOList(String json, T t) {
        net.sf.json.JSONArray jsonArray = (net.sf.json.JSONArray) net.sf.json.JSONArray.fromObject(json);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setPropertySetStrategy(new PropertyStrategyWrapper(PropertySetStrategy.DEFAULT));
        jsonConfig.setRootClass(t.getClass());
        jsonConfig.setArrayMode(JsonConfig.MODE_LIST);
        @SuppressWarnings("unchecked")
        List<T> results = (List<T>) net.sf.json.JSONSerializer.toJava(jsonArray, jsonConfig);

        return results;
    }
}